package cn.pegasus	.teamwork.interfaces.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.iyizhan.teamwork.base.util.ObjectUtil;
import cn.iyizhan.teamwork.base.util.ParameterEunm;
import cn.iyizhan.teamwork.base.util.http.HttpUtil;
import cn.pegasus.teamwork.interfaces.entity.BussInterfaceInfo;
import cn.pegasus.teamwork.interfaces.entity.BussInterfaceParam;
import cn.pegasus.teamwork.interfaces.mapper.BussInterfaceInfoMapper;
import cn.pegasus.teamwork.interfaces.service.BussInterfaceInfoService;
import cn.pegasus.teamwork.interfaces.service.BussInterfaceParamService;
import cn.pegasus.teamwork.manager.controller.BaseManagerController;
import cn.pegasus.teamwork.manager.service.SysUcenterFunctionService;

/**
 * ClassName: BussInterfaceInfoController
 * 
 * @Description: TODO 接口管理
 * @author zhoulibo
 * @date 2015年11月13日
 */

@Controller
@RequestMapping("/intefaces/*")
public class BussInterfaceInfoController extends BaseManagerController<BussInterfaceInfo, BussInterfaceInfoMapper> {
	Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private BussInterfaceInfoService bussInterfaceInfoService;
	@Autowired
	private BussInterfaceParamService bussInterfaceParamService;
	@Autowired
	private SysUcenterFunctionService sysUcenterFunctionService;

	@Autowired
	public BussInterfaceInfoController(
			BussInterfaceInfoService bussInterfaceInfoService) {
		setBaseService(bussInterfaceInfoService);
	}

	/**
	 * @Description: 获取接口信息以及接口参数信息
	 * @param map
	 * @return
	 * @throws Exception 
	 * @throws NumberFormatException 
	 * @throws
	 * @author zhoulibo
	 * @date 2015年11月16日
	 */
	@RequestMapping(value = "/getInterfaceInfo")
	public ModelAndView getInterfaceInfo(@RequestParam Map<String, Object> map) throws Exception {
		ModelAndView view = new ModelAndView("interfaces/interface-info-list");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String interfaceId = map.get("interfaceId")==null?"":map.get("interfaceId").toString();
		if(null != interfaceId && interfaceId.length() > 0){
			resultMap = bussInterfaceInfoService.getBussInterfaceInfoAll(Integer.valueOf(interfaceId));
			view.addObject("interfaceLists", resultMap);	
			view.addObject("interfaceId", interfaceId);	
		}
		
		return view;
	}

	/**
	 * @Description: TODO 接口列表
	 * @param map
	 * @return
	 * @throws
	 * @author zhoulibo
	 * @date 2015年11月16日
	 */
	@RequestMapping(value = "/getList")
	public ModelAndView getList(@RequestParam Map<String, Object> map) {
		ModelAndView view = new ModelAndView("interfaces/list");
		try {
			String appId = map.get("appId").toString();
			List<BussInterfaceInfo> list = bussInterfaceInfoService
					.selectInterfaceInfo(map);
			view.addObject("interfaceList", list);	
			view.addObject("appId", appId);	
		} catch (Exception e) {
			logger.error("查询接口列表失败", e);
		}
		return view;
	}

	/**
	 * @Description: TODO 添加接口弹窗
	 * @param map
	 * @return
	 * @throws
	 * @author zhoulibo
	 * @date 2015年11月16日
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView editInterfaceInfo(@RequestParam Map<String, Object> map) {
		ModelAndView mv = null;
		try {
			mv = new ModelAndView("interfaces/edit");
			if (map.get("id") != null && !"".equals(map.get("id").toString())) {
				BussInterfaceInfo interfaceInfo = bussInterfaceInfoService
						.detail(map);
				mv.addObject("interfaceInfo", interfaceInfo);
			} else {
				BussInterfaceInfo interfaceInfo = new BussInterfaceInfo();
				interfaceInfo.setAppId(Integer.parseInt(map.get("appId")
						.toString()));
				mv.addObject("interfaceInfo", interfaceInfo);
			}
		} catch (Exception e) {
			mv.addObject(ParameterEunm.ERROR_500_CODE.getBackParameter()
					.toString(), ParameterEunm.ERROR_500_CODE
					.getParameterName());
			logger.error("添加接口弹窗失败", e);
		}
		return mv;
	}

	/**
	 * @Description: TODO 提交添加接口数据
	 * @param map
	 * @return
	 * @throws
	 * @author zhoulibo
	 * @date 2015年11月16日
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Map<String, Object> add(@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = null;
		try {
			resultMap = bussInterfaceInfoService.addInterfaceInfo(map,
					getAdmin().getId());
		} catch (Exception e) {
			logger.error("提交添加接口数据失败", e);
		}
		return resultMap;
	}

	/**
	 * @Description: TODO 修改接口信息
	 * @param map
	 * @return
	 * @throws
	 * @author zhoulibo
	 * @date 2015年11月16日
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Map<String, Object> InterfaceInfo(
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = null;
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "id" },
				map);
		if (isNotNull) {
			try {
				resultMap = bussInterfaceInfoService.updateInterfaceInfo(map,
						getAdmin().getId());
			} catch (Exception e) {
				logger.error("修改接口失败", e);
			}
		}

		return resultMap;
	}

	/**
	 * @Description: TODO 删除接口
	 * @param map
	 * @return
	 * @throws
	 * @author zhoulibo
	 * @date 2015年11月16日
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Map<String, Object> delete(@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = null;
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "id" },
				map);
		if (isNotNull) {
			try {
				resultMap = bussInterfaceInfoService.deleteInterfaceInfo(map,
						getAdmin().getId());
			} catch (Exception e) {
				logger.error("删除接口失败", e);
			}
		}
		return resultMap;
	}

	/**
	 * @Title: interfaceTest
	 * @Description: TODO(测试接口页面跳转)
	 * @param @param map
	 * @param @return 设定文件
	 * @return ModelAndView 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/interfaceTest", method = RequestMethod.GET)
	public ModelAndView interfaceTest(@RequestParam Map<String, Object> map) {
		ModelAndView mav = new ModelAndView("interfaces/interfaces-test");
		List<BussInterfaceParam> paramList = new ArrayList<BussInterfaceParam>();
//		String[] array = null;
		String result = null;
		BussInterfaceInfo bussInterfaceInfo = null;
		if (null != map.get("id")) {
			// 查询接口信息
			try {
				Integer id = Integer.valueOf(map.get("id").toString());
				bussInterfaceInfo = bussInterfaceInfoService
						.getBussInterfaceInfo(id);
				if (bussInterfaceInfo != null) {
					// 获取接口参数请求参数
					Map<String, Object> pMap = new HashMap<String, Object>();
					pMap.put("interfaceId", id);
					pMap.put("paramType", 1);
					paramList = bussInterfaceParamService.selectParam(pMap);
				}
				if (map.get("type") != null) {
					// 获取URL数值
					String httpUrl = map.get("url").toString();
					
//					array = UrlManager.post(httpUrl,
//							new HashMap<String, Object>());
//					result = array[0];
//					if(null==array[0] || "".equals(array[0])){
//						result = array[1];
//					}
					result = HttpUtil.httpPost(httpUrl, null);
					//由于前台界面是整个页面刷新，重新将最新的url设置到对象中在前台显示
					if(httpUrl.contains("?")){
						String[] urls =httpUrl.split("[?]");
						bussInterfaceInfo.setReqUrl(urls[0]);
					}
					// URL url = new URL(httpUrl);
					// HttpURLConnection connection = (HttpURLConnection)
					// url.openConnection();
					// connection.setRequestMethod("GET");
					// connection.connect();
					// InputStream is = connection.getInputStream();
					// reader = new BufferedReader(new InputStreamReader(is,
					// "UTF-8"));
					// String strRead = null;
					// while ((strRead = reader.readLine()) != null) {
					// sbf.append(strRead);
					// sbf.append("\r\n");
					// }
					// reader.close();
					// result = sbf.toString();
					// gson.toJson(result);
				}
				mav.addObject("interfaceInfo", bussInterfaceInfo);
				mav.addObject("paramList", paramList);
				mav.addObject("resultInfo", result);
			} catch (Exception e) {
				mav.addObject("interfaceInfo", bussInterfaceInfo);
				mav.addObject("paramList", paramList);
				mav.addObject("resultInfo", "查询某个接口信息失败:"+e.getMessage());
				logger.error("查询某个接口信息失败", e);
			}
		} else {
			mav.addObject("msg", -1);// ID不能为空
		}
		
		return mav;
	}
}
